/*
 * @Author: hua
 * @Date: 2020-04-01 16:25:40
 * @description: 请求封装
 * @LastEditors: hua
 * @LastEditTime: 2020-04-01 17:28:29
 */
import axios from 'axios'
import Toast from 'react-native-root-toast';
import Config from "react-native-config";
// 创建axios实例
const service = axios.create({
  baseURL: Config.API_URL, // api的base_url
  timeout: 15000// 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  let token = "";
  if (token) {
    config.headers['Authorization'] = 'Bearer '+ token // 让每个请求携带自定义token 请根据实际情况自行修改
  } 
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
   /**
    * error为true时 显示msg提示信息
    */
    const res = response.data
    // 请求成功
    if (res.code === 0) {
      return res
    }
    // Token鉴权失败
    if (res.code === 401) {
     
      return Promise.reject('error')
    }
    Toast.show('This is a message', {
        duration: Toast.durations.LONG,
        position: Toast.positions.CENTER
    });
    return Promise.reject('error')
  },
  error => {
    /* 网络超时处理 */
    if (error == 'Error: timeout of 15000ms exceeded') {
        Toast.show('This is a message', {
            duration: Toast.durations.LONG,
            position: Toast.positions.CENTER
        });
        return Promise.reject('error')
    }
    /* 网络无响应处理 */
    if(typeof(error.response) == 'undefined'){
      if(error == 'Error: Network Error'){
        Toast.show('This is a message', {
            duration: Toast.durations.LONG,
            position: Toast.positions.CENTER
        });
        return Promise.reject('error')
      }
    }
    return Promise.reject(error)
  }
)

export default service